package com.south.base.test.arithmetic;

import java.util.HashMap;
import java.util.Map;

/**
 * 数组中，寻找和为固定值的元素下标
 */
public class TwoNums {
    public int[] twoSum1(int[] nums, int target) {
        boolean flag = false;
        int i, l = 0;
        for (i = 0; i < nums.length - 1; i++) {
            for (l = i + 1; l < nums.length; l++) {
                if (nums[i] + nums[l] == target) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                break;
            }
        }
        if (!flag) {
            throw new IllegalArgumentException("无解");
        }
        return new int[]{i, l};
    }

    public int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], i);
        }
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement) && map.get(complement) != i) {
                return new int[]{i, map.get(complement)};
            }
        }
        throw new IllegalArgumentException("无解");
    }

    public int[] twoSum3(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[]{map.get(complement), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("无解");
    }
}
